import { Inject, Injectable } from '@nestjs/common';
import { access, readFile, writeFile } from 'fs/promises';
import { DbModuleOptions } from './db.module';

@Injectable()
export class DbService {
  constructor(
    @Inject('OPTIONS')
    private options: DbModuleOptions
  ) {}

  async read() {
    const fileath = this.options.path;
    try {
      await access(fileath);
    } catch (e) {
      return [];
    }

    const str = await readFile(fileath, 'utf-8');

    if (!str) {
      return [];
    }
    return JSON.parse(str);
  }

  async write(obj: Record<string, any>) {
    await writeFile(this.options.path, JSON.stringify(obj || []), {
      encoding: 'utf-8',
    });
  }
}
